<template>
	<view class="chat-container">
		<!-- 聊天消息列表 -->
		<scroll-view class="message-list" scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true" @scrolltoupper="loadMoreMessages" :scroll-into-view="scrollToMessageId">
			<view v-for="(item, index) in messageList" :key="index" class="message-item"
				:class="item.type === 'driver' ? 'driver' : 'passenger'"
				:id="'msg-' + index">
				<view class="avatar">
					<image :src="item.type === 'driver' ? 'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/driver.jpg' : passengerUrl"
						mode="aspectFill"></image>
				</view>
				<view class="message-content">
					<text class="message-text">{{item.content}}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 输入框区域 -->
		<view class="input-area">
			<input type="text" v-model="inputMessage" placeholder="请输入消息" class="message-input" />
			<button @tap="sendMessage" class="send-btn">发送</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				driverId:"",
				passengerUrl:"",
				messageList: [
				],
				inputMessage: '',
				scrollTop: 0,
				oldScrollTop: 0,
				scrollToMessageId: '',
				socket: null // 将socket实例保存为组件数据
			}
		},
		onLoad(options) {
			if (options.driverId) {
			        this.driverId = options.driverId;
			        console.log('司机ID:', this.driverId);
			    }
			// 页面加载完成实现调用websocket
			this.initWebSocket();
		},
		onUnload() {
			// 组件卸载时关闭连接
			if (this.socket) {
				this.socket.close();
			}
		},
		methods: {
			initWebSocket() {
				//获取乘客的token
				const token = uni.getStorageSync('token');
				//获取乘客信息
				const user = uni.getStorageSync('user');
				this.passengerUrl = user.avatar;
				console.log(user.userId)
				console.log(token)
				this.socket = uni.connectSocket({
					url: 'ws://127.0.0.1:8005/chat',
					header: {
						'Cookie': 'token=' + token, //redis中存放用户信息的key值
						'sender_type': 'passenger', //发送方类型
						'conversationId': 'passenger_' + user.userId + '-driver_'+  this.driverId, //历史记录id
					},
					success: () => console.log('连接建立中...')
				});

				this.socket.onOpen(() => {
					console.log('WebSocket连接已打开');
				});

				this.socket.onMessage(res => {
					console.log('收到消息:', res.data);
					const msg = JSON.parse(res.data)
					console.log(msg);
					console.log("res.data.senderType:",msg.senderType)
					console.log("res.data.content:",msg.content)
					this.messageList.push({
						type: msg.senderType,
						content: msg.content // 假设后端返回JSON格式
					});
					this.scrollToBottom();
				});

				this.socket.onError(err => {
					console.error('WebSocket错误:', err);
				});

				this.socket.onClose(() => {
					console.log('WebSocket连接已关闭');
				});
			},
			sendMessage() {
				if (!this.inputMessage.trim()) return;

				// 添加乘客新消息
				this.messageList.push({
					type: 'passenger',
					content: this.inputMessage
				});
				
				//发送消息
				if (this.socket) {
					const message = {
						toUserId: this.driverId,
						content: this.inputMessage
					};
					console.log(message)
					this.socket.send({
						data: JSON.stringify(message),
						success: () => {
							console.log('消息发送成功');
							this.inputMessage = '';
							this.scrollToBottom();
						},
						fail: (err) => {
							console.error('消息发送失败:', err);
						}
					});
				} else {
					console.error('WebSocket连接未建立');
				}
			},
			scrollToBottom() {
				// 使用 nextTick 确保在 DOM 更新后执行滚动
				this.$nextTick(() => {
					if (this.messageList.length > 0) {
						// 使用最后一条消息的ID进行滚动
						this.scrollToMessageId = 'msg-' + (this.messageList.length - 1);
						
						// 同时使用scrollTop作为备选方案
						const query = uni.createSelectorQuery().in(this);
						query.select('.message-list').boundingClientRect(data => {
							if (data) {
								this.scrollTop = data.height * 2;
							}
						}).exec();
					}
				});
			},
			// 加载更多历史消息
			loadMoreMessages() {
				// TODO: 实现加载更多历史消息的逻辑
				console.log('加载更多历史消息');
			},
			// 监听消息列表滚动
			onMessageListScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
			}
		},
		watch: {
			// 监听消息列表变化
			messageList: {
				handler(newVal) {
					if (newVal.length > 0) {
						this.scrollToBottom();
					}
				},
				deep: true
			}
		}
	}
</script>

<style>
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
		position: relative; /* 添加相对定位 */
	}

	.message-list {
		flex: 1;
		padding: 20rpx;
		padding-bottom: 120rpx; /* 为输入框留出空间 */
		box-sizing: border-box;
		height: calc(100vh - 120rpx); /* 减去输入框的高度 */
		-webkit-overflow-scrolling: touch; /* 增加弹性滚动 */
		position: relative;
	}

	.message-item {
		display: flex;
		margin-bottom: 30rpx;
		opacity: 0;
		animation: fadeIn 0.3s ease forwards;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.message-item.driver {
		flex-direction: row;
	}

	.message-item.passenger {
		flex-direction: row-reverse;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		margin: 0 20rpx;
	}

	.avatar image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.message-content {
		max-width: 60%;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;
	}

	.driver .message-content {
		background-color: #007AFF;
	}

	.driver .message-text {
		color: #fff;
	}

	.passenger .message-content {
		background-color: #fff;
	}

	.message-text {
		font-size: 28rpx;
		line-height: 1.5;
	}

	.input-area {
		display: flex;
		padding: 20rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		position: fixed; /* 固定定位 */
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 100;
		box-sizing: border-box;
		height: 120rpx;
	}

	.message-input {
		flex: 1;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		padding: 0 30rpx;
		margin-right: 20rpx;
	}

	.send-btn {
		width: 120rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #007AFF;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
	}
</style>